package com.jsl.action;

import com.api.system.language.autoTranslate.MD5;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

public class BatchDeleteDaibanMsgAction {

    private static final Log log = LogFactory.getLog(DaibanAction.class);
    private static final String appSecret = "e89277cb47e64f3d9473c401b559ff11";
    private static final String appId = "d12733aa0b68498fa6e13e4843c171de";
    private static final String url = "https://www.fjjslds.com";
    private static final String CODE = "S20250606002";

    //

    public static void main(String[] args) throws Exception {
        System.out.println("开始测试接口");
        String token = getToken();
        String[] values = {
                "384470"
        };
        for (String value : values) {
            sendRequest(token,value);
            Thread.sleep(2000);
        }

    }


    /**
     * 签名生成函数
     *
     * @param map
     * @param allrowEmpty
     * @return
     */
    private static String mapSortToUrlParam(Map<String, String> map, Boolean allrowEmpty) {
        List<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // 返回相反的compare
                return o1.compareTo(o2);
            }
        });
        Iterator<String> iter = keys.iterator();
        StringBuffer signStr = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = map.get(key);
            if (!allrowEmpty && value == null) {// 不允许值为空
                continue;
            }
            if (signStr.length() > 0) {
                signStr.append("&");
            }
            signStr.append(key).append("=").append(value);
        }
        //System.out.println(signStr.toString());
        return signStr.toString();
    }

    /**
     * <p>Title: postForm</p>
     * <p>Description: 请求</p>
     *
     * @param url
     * @param headMap
     * @param params
     * @return
     * @throws Exception
     */
    private static String postForm(String url, Map<String, Object> headMap, Map<String, String> params) throws Exception {
        try {
            // post请求
            HttpPost httpPost = new HttpPost(url);
            if (headMap != null && !headMap.isEmpty()) {// 头部
                for (String key : headMap.keySet()) {
                    httpPost.setHeader(key, headMap.get(key) != null ? headMap.get(key).toString() : "");
                }
            }
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    nvps.add(new BasicNameValuePair(key, params.get(key) != null ? params.get(key).toString() : ""));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            int socketTimeout = 30000;
            int connectionTimeout = 30000;
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectionTimeout).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 发送请求
            HttpClient httpclient = null;
            httpclient = HttpClientBuilder.create().build();
            HttpResponse httpresponse = httpclient.execute(httpPost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            return body;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private static void sendRequest(String token,String piid) throws Exception {

        //[结果要判断，这里只是做个样例]
        System.out.println("token:" + token);

        // 调用spi接口
        String url2 = url + "/intf";
        // 生成签名的参数
        Map<String, String> signParams = buildSignParams(piid);
        String sign2 = MD5.md5(mapSortToUrlParam(signParams, true));
        signParams.put("sign", sign2);

        Map<String, Object> head = buildHeaders(token);
        System.out.println(signParams);
        String jsonString = postForm(url2, head, signParams);
        System.out.println(jsonString);

    }
    private static String getToken() throws Exception {
        //生成签名的参数
        Map<String, String> param1 = new HashMap<>();
        param1.put("appId", appId);
        param1.put("appSecret", appSecret);
        param1.put("timestamp", String.valueOf(new Date().getTime()));
        String param1str = mapSortToUrlParam(param1, true);
        String sign = MD5.md5(param1str);
        param1.put("sign", sign);
        String url1 = url + "/spiToken";

        //获取token的返回结果
        String tokenresult = postForm(url1, null, param1);

        //解析结果中token[结果要判断，这里只是做个样例]
        JSONObject jsonObject = JSONObject.fromObject(tokenresult);

        String token = jsonObject.getString("data");
        log.info("获取到token:"+token);
        //[结果要判断，这里只是做个样例]
        return token;
    }

    private static Map<String, String> buildSignParams(String piid) {
        Map<String, String> params = new HashMap<>();
        params.put("code", CODE);
        params.put("appSecret", appSecret);
        params.put("timestamp", String.valueOf(new Date().getTime()));
        params.put("piid", piid);
        return params;
    }

    private static Map<String, Object> buildHeaders(String token) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("access_token", token);
        return headers;
    }

}
